package com.hongxun.design.activitys.serviceandclient;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.FilesViewActivity;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.utils.socketutil.LongWriterAndReader;
import com.hongxun.design.bean.service.MessageData;
import com.hongxun.design.utils.socketutil.ReciveAndSend;


/**
 * Created by zerdoor_pc on 2016/4/22.
 * 热点客户端
 */
public class ClientLong extends BaseActivity {
    public static final Object locked = new Object();
    public static final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(
            1024 * 100);
    private int prot = 8088;
    private MessageData messageData;
    private EditText edtext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_socket);
        MyLog.L(MyApp.AppName + ": client");
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("client");
        Button btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), FilesViewActivity.class);
                startActivityForResult(intent, 0);
            }
        });

        edtext = (EditText) findViewById(R.id.edtext);
        Button btnSendtext = (Button) findViewById(R.id.btnSendtext);
        btnSendtext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageData = ReciveAndSend.getMessageData(1, edtext.getText().toString(), "");
            }
        });

        start();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //选择了文件发送
        if (resultCode == RESULT_OK) {
            String fileName = data.getStringExtra("FileName");
            String path = data.getStringExtra("FilePath");
            messageData=ReciveAndSend.getMessageData(4, path, fileName);
//            messageData = ReciveAndSend.getMessageData(1, "消息", "");
        }
    }


    /**
     * 发送线程*
     */
    private Boolean flag=false;
    class SendThread extends Thread {
        private Socket socket;
        public SendThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            while (true) {
                try {
//                    int DataType=0;
//                    String send = getSend();
//                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//                    pw.write(DataType);
//                    pw.write(send);
//                    pw.flush();
                    Thread.sleep(5000);
                    if (!flag){
                        if (messageData != null) {
                            MyLog.L(MyApp.AppName + "发送消息1");
                            flag=true;
                            LongWriterAndReader.writer(socket.getOutputStream(), messageData, true);
                            flag=true;
                            messageData=null;
                        } else {
                            LongWriterAndReader.writer(socket.getOutputStream(), 0,true);
                        }
                    }

                 } catch (Exception e) {
                    MyLog.L(MyApp.AppName + "e="+e.toString());
                }
            }
        }

        public String getSend() throws InterruptedException {
            Thread.sleep(3000);
            return "<SOAP-ENV:Envelope>" + System.currentTimeMillis() + "</SOAP-ENV:Envelope>";
        }
    }

    /**
     * 接收线程*
     */
    class ReceiveThread extends Thread {
        private Socket socket;

        public ReceiveThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            while (true) {
                try {
//                    Reader reader = new InputStreamReader(socket.getInputStream());
//                    CharBuffer charBuffer = CharBuffer.allocate(8192);
//                    int index = -1;
//                    while ((index = reader.read(charBuffer)) != -1) {
//                        charBuffer.flip();
//                        MyLog.L(MyApp.AppName + "client:接收：" + charBuffer.toString());
//                    }

                    if (LongWriterAndReader.reader(socket.getInputStream(), true,true).equals("0")){
                        flag=false;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                try {
                    socket = new Socket(GetServerIpAddress(), prot);
                    MyLog.L(MyApp.AppName + "读取ip="+GetServerIpAddress());
                    new SendThread(socket).start();
                    new ReceiveThread(socket).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    /**
     * 得到服务器的ip*
     */
    public String GetServerIpAddress() {
        @SuppressLint("WifiManagerLeak")
        WifiManager wifiManage = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        DhcpInfo info = wifiManage.getDhcpInfo();
        int i = info.serverAddress;
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                ((i >> 24) & 0xFF);
    }
}
